package com.sso.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import com.sso.gateway.domain.security.WhiteListDomainService;
import com.sso.gateway.client.UserInfo;
import com.sso.gateway.client.AuthServiceClient;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 认证过滤器
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    
    private final WhiteListDomainService whiteListDomainService;
    private final AuthServiceClient authServiceClient;

    public AuthFilter(WhiteListDomainService whiteListDomainService, AuthServiceClient authServiceClient) {
        this.whiteListDomainService = whiteListDomainService;
        this.authServiceClient = authServiceClient;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        
        // 白名单路径直接放行
        if (whiteListDomainService.isWhitePath(path)) {
            return chain.filter(exchange);
        }
        
        // 获取Authorization头
        String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (!StringUtils.hasText(authorization) || !authorization.startsWith("Bearer ")) {
            log.warn("请求路径 {} 缺少有效的Authorization头", path);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        
        // 调用认证服务验证令牌
        String token = authorization.substring(7);
        return authServiceClient.validateTokenWithAuthService(token)
                .flatMap(valid -> {
                    if (!Boolean.TRUE.equals(valid)) {
                        log.warn("请求路径 {} 的令牌无效", path);
                        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                        return exchange.getResponse().setComplete();
                    }
                    // 校验通过后获取用户信息并透传到下游
                    return authServiceClient.fetchUserInfoFromAuthService(token)
                            .defaultIfEmpty(new UserInfo())
                            .flatMap(userInfo -> {
                                ServerHttpRequest mutatedRequest = exchange.getRequest()
                                        .mutate()
                                        .header("X-User-Name", userInfo.getUsername() == null ? "" : userInfo.getUsername())
                                        .header("X-User-Nickname", userInfo.getNickname() == null ? "" : userInfo.getNickname())
                                        .header("X-User-RealName", userInfo.getRealName() == null ? "" : userInfo.getRealName())
                                        .build();
                                return chain.filter(exchange.mutate().request(mutatedRequest).build());
                            });
                });
        
    }
    
    @Override
    public int getOrder() {
        return -100;
    }
    

}